﻿package kliment.data {
	import flash.xml.XMLDocument;
	import flash.xml.XMLNode;
	import kliment.utils._Object;
	
	/**
	 * ...
	 * @author	Kliment
	 * @version	0.1.7
	 * 
	 * class name: kliment.data.XMLObject
	 */
	public dynamic class XMLObject {
		private static const _ignorKeys:Array = [0];
		private var _parent:XMLObject;
		private var _value:String;
		public var attributes:Object = null;
		
		public function get length():Number { return 1 }
		public function get parent():XMLObject { return _parent }
		
		/**
		 * 
		 * @param	value XMLDocument||XMLNode||String;
		 * @param	parent XMLObject = null
		 */
		public function XMLObject(value:* = null, parent:XMLObject = null) {
			if (parent != null) _parent = parent;
			
			if (value is XMLDocument){
				_parsNode(value.firstChild);
			} else if (value is XMLNode){
				_parsNode(value);
			} else  if (value is String) {
				var xmlDocument:XMLDocument = new XMLDocument();
				xmlDocument.ignoreWhite = true;
				xmlDocument.parseXML(value as String);
				_parsNode(xmlDocument.firstChild);
			} 
			
			this[0] = this;
		}
		
		private function _parsNode(xmlNode:XMLNode):void {
			if (xmlNode && xmlNode.attributes) 
				attributes = _Object.copy(xmlNode.attributes);
			_value = xmlNode.firstChild.nodeValue;
			var length:Number = xmlNode.childNodes.length;
			for (var i:Number = 0; i < length; ++i) {
				var node:XMLNode = xmlNode.childNodes[i];
				var nodeName:String = node.nodeName;
				if (node.nodeName) 
					_addValue(nodeName, new XMLObject(node, this));
			}
		}
		
		private function _addValue(name:String, value:XMLObject):void {
			if (this[name]) {
				if (!(this[name] is Array))
					this[name] = new Array(this[name]);
				this[name].push(value);
			} else {
				this[name] = value;
			}
		}
		
		private function _ignoredKey(key:*):Boolean {
			for (var i in _ignorKeys)
				if (_ignorKeys[i] == key)
					return true;
			return false;
		}
		
		public function toString():String {
			return _value;
		}
	}

}